package com.lagou.serialize;

import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

/**
 * @ClassName: RpcDecoder
 * @Description:  解码器实现：(需要编码器转换为请求对象)
 * @Version: v1.0.0
 * @Author: chendong
 * @Date: 2021/1/9
 * Modification History:
 * Date             Author      Version     Description
 * -------------------------------------------------------------
 * 2021/1/9         chendong       v1.0.0         创建
 */

public class RpcDecoder extends ByteToMessageDecoder {

    private Class<?> clazz;
    private Serializer serializer;


    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }


    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> list) throws Exception {
        //标记一下当前的readIndex的位置
        in.markReaderIndex();
        // 读取传送过来的消息的长度
        int dataLength = in.readInt();
        //读到的消息体长度为0，这是不应该出现的情况，这里出现这情况，关闭连接。
        if (dataLength < 0) {
            ctx.close();
        }
        byte[] body = new byte[dataLength];
        in.readBytes(body);
        Object object = serializer.deserialize(clazz, body);
        list.add(object);
    }
}
